import { request } from "../../utils/util";

Page({
  data: {
    region: ['四川省', '成都市', '武侯区'],
    form: {
      name: '',
      phone: '',
      province: '',
      city: '',
      area: '',
      address: '',
      is_default: 0,
    }
  },
  onInputChange(e) {
    const { value } = e.detail;
    const { name } = e.currentTarget.dataset;
    const { form } = this.data;
    this.setData({
      form: { ...form, [name]: value }
    });
  },
  toggleDefault () {
    this.setData({
      form: {
        ...this.data.form,
        is_default: this.data.form.is_default === 0 ? 1 : 0
      }
    })
  },
  bindRegionChange (e) {
    this.setData({
      region: e.detail.value
    })
  },
  save() {
    this.data.form.province = this.data.region[0];
    this.data.form.city = this.data.region[1];
    this.data.form.area = this.data.region[2];
    this.data.form.is_default = Number(this.data.form.is_default)
    let url = `/api/web/consignees`;
    let method = 'POST';
    if (this.options.id) {
      url = `/api/web/consignees/${this.options.id}`;
      method = 'PUT';
    }
    wx.showLoading({
      title: '加载中..',
      mask: true
    })
    request({
      url,
      method,
      data: this.data.form,
      success: ({ code, message }) => {
        wx.hideLoading()
        if (code === 200) {
          wx.navigateBack()
        } else {
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 获取单个地址
  getDetail() {
    wx.showLoading({
      title: '加载中..',
      mask: true
    })
    request({
      url: `/api/web/consignees/${this.options.id}`,
      success: ({ code, data }) => {
        wx.hideLoading()
        if (code === 200) {
          for (let key in this.data.form) {
            this.data.form[key] = data[key]
          }
          this.setData({
            form: this.data.form,
            region: [data.province, data.city, data.area]
          })
        }
      }
    })
  },
  onShow() {
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#000000',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
    if (this.options.id) {
      this.getDetail()
    }
  },
})
